package com.example.framework.filter;

import com.auth0.jwt.JWT;
import com.example.common.exception.JwtAuthenticationException;
import com.example.common.exception.ServiceException;
import com.example.common.utils.RedisUtil;
import com.example.framework.utils.TokenUtils;
import com.example.system.entity.User;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @Author 王鹤蒲
 * @Date 2023 09 16
 */


public class JwtAuthenticationFilter extends BasicAuthenticationFilter {


    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }


//    private static final String[] urls={"/test/**","/user/getCaptcha","/user/login","/user/register","/file/**","/swagger-ui/**", "/v3/**", "/error","/user/getCaptcha","/user/sendEmailCode","/user/verifyEmailCode","/user/isPhonenumberExist","/user/isUsernameExist","/user/isEmailExist","/user/verifyUserEmail","/user/updatePassword"};
//
//    @Override
//    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
//               String  url= request.getRequestURI();
//        return Stream.of(urls).anyMatch(x-> new AntPathMatcher().match(x,url));
//    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        System.out.println(request.getRequestURI()+"---------");
        User user= null;
        try {
            user = TokenUtils.verifyToken(token);
        } catch (ServiceException e) {
        request.setAttribute("JwtAuthenticationException",new JwtAuthenticationException( e.getMessage()));
         request.getRequestDispatcher("/throwJwtAuthenticatonException").forward(request,response);
         return ;
        }
        if(!RedisUtil.hasKey(String.valueOf(user.getUserId()))){
            request.setAttribute("JwtAuthenticationException",new JwtAuthenticationException("无token，请重新登录"));
            request.getRequestDispatcher("/throwJwtAuthenticatonException").forward(request,response);
            return ;
        }
        String redisToken=String.valueOf(RedisUtil.get(String.valueOf(user.getUserId())));
        if(!token.equals(redisToken)){
            request.setAttribute("JwtAuthenticationException",new JwtAuthenticationException("已在其他地方登录，继续访问请重新登录"));
            request.getRequestDispatcher("/throwJwtAuthenticatonException").forward(request,response);
            return ;
        }
        Integer userId = Integer.parseInt(JWT.decode(token).getAudience().get(0));
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), null, new ArrayList<>());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }


}
